import React, { useState } from 'react';
import styles from './index.less';
import { useTRState } from '@/utils';
import { useInterval } from 'ahooks';
import cls from 'classnames';
import { getDvaApp } from 'umi';
// components
import { Button, Form, notification, Space, Tooltip } from 'antd';
import { TRMessage } from '@/components';
import TextField from './components/TextField';
import Password from './components/Password';
import { phoneReg, passwordReg } from '@/utils/regExp';
import { CloseOutlined } from '@/utils/antdIcons';
// api
import { getverificationCode, SetverificationCode, SetPassword } from '@/services/user';
import { fakeAccountLogin } from '@/services/login';
import { HttpCode } from '@/utils/contacts';

const UserLogin = () => {
  const [form] = Form.useForm();

  const [title, setTitle] = useState('登录');
  const [count, setCount] = useState(0);
  const [counting, setCounting] = useState(undefined);
  const [loading, setLoading] = useState(false);
  const [loginErr, setLoginErr] = useState('');
  const [toolTipVisible, setToolTipVisible] = useState(false); // 密码提示框
  const [formValues, setFormValues] = useTRState({
    username: '',
    password: '',
    phoneNum: '', // 手机号，动态校验使用
    verificationCode: '',
    rePassword1: '',
    rePassword2: '',
  });

  const startCounting = () => {
    setCount(60);
    setCounting(1000);
  };
  const endCounting = () => {
    setCounting(undefined);
  };

  useInterval(() => {
    if (count > 0) {
      setCount(count - 1);
    } else {
      endCounting();
    }
  }, counting);

  const goForget = () => {
    const phoneNum = phoneReg.test(formValues.username) ? formValues.username : '';
    setFormValues({
      phoneNum,
      verificationCode: '',
    });
    setTitle('忘记密码');
    setLoginErr('');
    form.setFieldsValue({
      phoneNum,
      verificationCode: '',
    });
  };

  const goBackLogin = () => {
    setFormValues({
      phoneNum: '',
      verificationCode: '',
      rePassword1: '',
      rePassword2: '',
    });
    setTitle('登录');
  };

  // 登录提交
  const submitLogin = async () => {
    setLoading(true);
    let errMsg = '';
    const res = await fakeAccountLogin({
      username: formValues.username,
      password: formValues.password,
      edition: 'W1.0',
      source: 'web',
    });
    if (res?.statusCode === HttpCode.SUCCESS) {
      const token = res?.token ?? '';
      // recordAccount(formValues);
      // 保存密码
      let updateFlag = false;
      const { username, password } = formValues;
      const recordList = JSON.parse(localStorage?.recordPassWord || '[]');
      const existUserNameInd = recordList.findIndex((item) => item.username === username);
      if (
        !(
          existUserNameInd !== -1 &&
          simpleDecrypt(recordList[existUserNameInd].password || '') === password
        )
      ) {
        if (existUserNameInd !== -1) updateFlag = true;
        if (updateFlag) {
          recordList.splice(existUserNameInd, 1);
          localStorage.recordPassWord = JSON.stringify([
            ...recordList,
            { username, password: simpleEncrypt(password) },
          ]);
        } else {
          if (JSON.parse(localStorage.recordPassWord ?? '[]')?.length < 10) {
            localStorage.recordPassWord = JSON.stringify([
              ...recordList,
              { username, password: simpleEncrypt(password) },
            ]);
          }
        }
      }
      const { dispatch } = getDvaApp()._store;
      dispatch({
        type: 'login/login',
        payload: token,
      });
    } else {
      errMsg = res?.message ?? '';
    }
    setLoading(false);
    setLoginErr(errMsg);
  };

  // 简单加密（编码）
  function simpleEncrypt(text) {
    // 使用 btoa 进行 Base64 编码
    return btoa(unescape(encodeURIComponent(text)));
  }
  // 简单解密（解码）
  function simpleDecrypt(encryptedText) {
    // 使用 atob 进行 Base64 解码
    return decodeURIComponent(escape(atob(encryptedText)));
  }
  // 保存账号密码
  // const recordAccount = ({ username, password }) => {
  //   if (!username || !password) return;
  //   let updateFlag = false;
  //   const recordList = JSON.parse(localStorage?.recordPassWord || '[]');
  //   const existUserNameInd = recordList.findIndex((item) => item.username === username);
  //   if (
  //     existUserNameInd !== -1 &&
  //     simpleDecrypt(recordList[existUserNameInd].password || '') === password
  //   )
  //     return;
  //   if (existUserNameInd !== -1) updateFlag = true;
  //   // 提示保存密码
  //   notification.open({
  //     message: updateFlag ? '密码有改动，是否需要保存新的密码？' : '要保存密码吗？',
  //     description: (
  //       <div>
  //         <div>
  //           当前浏览器不会保存您的账号密码，是否需要保存？下次登录可以直接使用保存的账号密码登录。
  //         </div>
  //         <Space style={{ display: 'flex', justifyContent: 'flex-end', marginTop: 16 }}>
  //           <Button
  //             style={{ borderColor: '#d9d9d9', borderRadius: 8 }}
  //             onClick={() => notification.destroy()}
  //           >
  //             不保存
  //           </Button>
  //           <Button
  //             type="primary"
  //             style={{ borderRadius: 8 }}
  //             onClick={() => {
  //               const recordList = JSON.parse(localStorage?.recordPassWord || '[]');
  //               if (updateFlag) {
  //                 recordList.splice(existUserNameInd, 1);
  //                 localStorage.recordPassWord = JSON.stringify([
  //                   ...recordList,
  //                   { username, password: simpleEncrypt(password) },
  //                 ]);
  //                 notification.destroy();
  //                 return;
  //               }
  //               localStorage.recordPassWord = JSON.stringify([
  //                 ...recordList,
  //                 { username, password: simpleEncrypt(password) },
  //               ]);
  //               notification.destroy();
  //             }}
  //           >
  //             保存
  //           </Button>
  //         </Space>
  //       </div>
  //     ),
  //     placement: 'topRight',
  //     duration: null,
  //   });
  // };
  // 关闭密码提示框
  const closeToolTip = () => {
    setToolTipVisible(false);
  };
  // 密码提示内容
  const recordToolTipContent = () => {
    function textFotmat(text) {
      return text?.replace(/./g, '•');
    }
    const recordList = JSON.parse(localStorage?.recordPassWord || '[]');
    return (
      <div className={styles.record_tooltipContent}>
        <div className={styles.record_tooltipContent_title}>
          <div>保存的账号密码</div>
          <CloseOutlined onClick={closeToolTip} className={styles.record_tooltipContent_icon} />
        </div>
        {recordList.map((item, index) => (
          <div
            key={item.username}
            className={styles.record_tooltipContent_item}
            onClick={() => {
              const password = simpleDecrypt(item.password);
              form.setFieldsValue({ ...item, password });
              setFormValues({ ...item, password });
            }}
          >
            <div className={styles.record_tooltipContent_item_account}>
              <div>{item.username}</div>
              <div style={{ paddingLeft: 2 }}>{textFotmat(item.password)}</div>
            </div>
            <CloseOutlined
              onClick={(e) => {
                e.stopPropagation();
                const recordList = JSON.parse(localStorage?.recordPassWord || '[]');
                recordList.splice(index, 1);
                localStorage.recordPassWord = JSON.stringify(recordList);
              }}
              className={styles.record_tooltipContent_item_icon}
            />
          </div>
        ))}
      </div>
    );
  };
  const onValuesChange = (changedValues) => {
    if (changedValues?.username && toolTipVisible) {
      setToolTipVisible(false);
    }
  };

  const getCode = async () => {
    startCounting();
    const { phoneNum } = formValues;
    const res = await getverificationCode({
      phoneNum,
      sendType: true,
    });
    if (res?.statusCode !== HttpCode.SUCCESS) {
      endCounting();
      TRMessage.error(res?.message || '获取验证码失败，请稍后重试');
    }
  };

  const submitForget = async () => {
    const { phoneNum, verificationCode } = formValues;
    setLoading(true);
    const res = await SetverificationCode({
      phoneNum,
      verificationCode,
      professionalType: 0,
    });
    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      setTitle('设置密码');
    } else {
      TRMessage.error(res?.message || '手机验证失败');
    }
  };

  // 设置密码提交
  const submitPwd = async () => {
    const { phoneNum, verificationCode, rePassword1 } = formValues;
    setLoading(true);
    const res = await SetPassword({
      phoneNum,
      verilicationCode: verificationCode,
      password: rePassword1,
    });
    setLoading(false);
    if (res?.statusCode === HttpCode.SUCCESS) {
      TRMessage.success('密码设置成功');
      goBackLogin();
    } else {
      TRMessage.error('密码设置失败');
    }
  };

  // 登录
  const LoginForm = () => {
    return (
      <div style={{ position: 'relative' }}>
        <Tooltip
          placement="bottomLeft"
          title={recordToolTipContent}
          visible={toolTipVisible}
          color="#fff"
          overlayInnerStyle={{ width: '350px', borderRadius: '8px' }}
        >
          <div style={{ position: 'absolute', top: '45px', left: '5%' }} />
        </Tooltip>
        <Form form={form} onFinish={submitLogin} onValuesChange={onValuesChange}>
          <Form.Item name="username" rules={[{ required: true, message: '手机号不能为空' }]}>
            <TextField
              focusFn={() => {
                if (
                  !form.getFieldsValue()?.username &&
                  JSON.parse(localStorage?.recordPassWord || '[]')?.length
                ) {
                  setToolTipVisible(true);
                }
              }}
              blurFn={() => setTimeout(() => setToolTipVisible(false), 250)}
              label="手机号"
              onChange={(username) => setFormValues({ username })}
              noremember={true}
            />
          </Form.Item>
          <Form.Item
            name="password"
            rules={[{ required: true, message: '密码不能为空' }]}
            help={loginErr}
          >
            <Password onChange={(password) => setFormValues({ password })} noremember={true} />
          </Form.Item>
          <Form.Item shouldUpdate>
            {() => (
              <Button
                className={styles.submit}
                type="primary"
                htmlType="submit"
                size="large"
                block
                loading={loading}
              >
                登录
              </Button>
            )}
          </Form.Item>
        </Form>
        {/* <div className={styles.foot}>
          <div />
          <div>
            <span className={styles.link} onClick={goForget}>
              忘记密码
            </span>
          </div>
        </div> */}
      </div>
    );
  };

  // 忘记密码
  const ForgetForm = () => {
    return (
      <>
        <Form form={form} onFinish={submitForget}>
          <Form.Item
            name="phoneNum"
            rules={[
              { required: true, message: '手机号不能为空' },
              { pattern: phoneReg, message: '手机号格式不正确' },
            ]}
          >
            <TextField label={'手机号'} onChange={(phoneNum) => setFormValues({ phoneNum })} />
          </Form.Item>
          <Form.Item
            name="verificationCode"
            rules={[{ required: true, message: '验证码不能为空' }]}
          >
            <TextField
              label={'验证码'}
              onChange={(verificationCode) => setFormValues({ verificationCode })}
              suffix={
                <div
                  className={cls({
                    [styles.suffix_countdown]: true,
                    [styles.disabled]: !phoneReg.test(formValues.phoneNum),
                  })}
                >
                  {counting ? (
                    `${count}s`
                  ) : (
                    <span className={styles.btn} onClick={getCode}>
                      获取验证码
                    </span>
                  )}
                </div>
              }
            />
          </Form.Item>
          <Form.Item shouldUpdate>
            {() => (
              <Button
                className={styles.submit}
                type="primary"
                htmlType="submit"
                size="large"
                block
                loading={loading}
              >
                提交
              </Button>
            )}
          </Form.Item>
        </Form>
        <div className={styles.foot}>
          <div />
          <div>
            <span className={styles.link} onClick={goBackLogin}>
              返回登录
            </span>
          </div>
        </div>
      </>
    );
  };

  // 设置密码
  const pwdForm = () => {
    return (
      <>
        <Form form={form} onFinish={submitPwd}>
          <Form.Item
            name="rePassword1"
            initialValue=""
            rules={[
              { required: true, message: '密码不可设置为空' },
              {
                pattern: passwordReg,
                message: '密码长度要求8-16位,含大小写字母和数字组合',
              },
            ]}
          >
            <Password noremember onChange={(rePassword1) => setFormValues({ rePassword1 })} />
          </Form.Item>
          <Form.Item
            name="rePassword2"
            initialValue=""
            rules={[
              {
                validator: (w, value, callback) => {
                  const newPwd = form.getFieldValue('rePassword1');
                  if (value !== newPwd) {
                    callback('您两次输入的密码不一致,请重新输入');
                  }
                  callback();
                },
              },
            ]}
          >
            <Password
              label="确认密码"
              noremember
              onChange={(rePassword2) => setFormValues({ rePassword2 })}
            />
          </Form.Item>
          <Form.Item shouldUpdate>
            {() => (
              <Button
                className={styles.submit}
                type="primary"
                htmlType="submit"
                size="large"
                block
                loading={loading}
              >
                提交
              </Button>
            )}
          </Form.Item>
        </Form>
        <div className={styles.foot}>
          <div />
          <div>
            <span className={styles.link} onClick={goBackLogin}>
              返回登录
            </span>
          </div>
        </div>
      </>
    );
  };

  return (
    <div className={styles.login}>
      <div className={styles.login_title}>{title}</div>
      {title === '登录' && LoginForm()}
      {title === '忘记密码' && ForgetForm()}
      {title === '设置密码' && pwdForm()}
    </div>
  );
};

export default UserLogin;
